//
//  WBComposeController.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/24.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 撰写微博控制器
class WBComposeController: UIViewController, UITextViewDelegate {
    
    /// 文本编辑视图
    @IBOutlet weak var textView: WBComposeTextView!
    /// 底部工具栏
    @IBOutlet weak var toolbar: UIToolbar!
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet weak var toolbarBottomConstr: NSLayoutConstraint!
    
    lazy var sendBtn: UIButton = {
        let btn = UIButton.az_textButton(text: "发布", fontSize: 16, normalColor: .white, highlightedColor: .darkGray, backgroundImage: UIImage(named: "common_button_orange")?.strenchImage())
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 35)
        btn.isEnabled = false
        btn.addTarget(self, action: #selector(postStatus), for: .touchUpInside)

        return btn
    }()
    
    /// 表情输入视图
    lazy var emotionView: CZEmotionInputView = CZEmotionInputView.inputView { [weak self] (emotion) in
        self?.textView.insertEmotion(em: emotion)
    }

    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        // 监听键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        textView.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
    }
    
    deinit {
       NotificationCenter.default.removeObserver(self)
    }

    //MARK: - 代理
    func textViewDidChange(_ textView: UITextView) {
        sendBtn.isEnabled = textView.hasText
    }
}

// MARK: - 按钮监听方法
private extension WBComposeController {
    @objc func keyboardChanged(noti: Notification) {
        
        guard let rect = (noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue)?.cgRectValue,
            let duration = (noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? NSNumber)?.doubleValue else {return}
        
        toolbarBottomConstr.constant = view.bounds.height - rect.origin.y
        
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    /// 发送微博
    @objc func postStatus() {
        WBNetworkManager.shared.postStatus(textView.emotionText, image: nil) { (json, isSuccess) in
            
            SVProgressHUD.setDefaultStyle(.dark)
            let message = isSuccess ? "发布成功" : "网络不给力"
            SVProgressHUD.showInfo(withStatus: message)
            
            
            if isSuccess {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                    SVProgressHUD.setDefaultStyle(.light)
                    self.close()
                }
            }
        }    }
    
    @objc func close() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc func emoticonKeyboard() {
        debugPrint("show emoticon keyboard")
        
        let keyboardView = emotionView
        
        textView.inputView = (textView.inputView == nil) ? keyboardView : nil
        
        toolbarBottomConstr.constant = 255
        
        textView.reloadInputViews()
    }
}

// MARK: - UI相关
extension WBComposeController {
    func setupUI() {
        setupNav()
        setupToolbar()
    }
    
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close), isBack: false)
        sendBtn.isEnabled = false
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        navigationItem.titleView = titleLabel
    }
    
    private func setupToolbar() {
        
        let itemSettings = [["imageName":"compose_toolbar_picture"],
                            ["imageName":"compose_mentionbutton_background"],
                            ["imageName":"compose_trendbutton_background"],
                            ["imageName":"compose_emoticonbutton_background", "actionName":"emoticonKeyboard"],
                            ["imageName":"message_add_background"]]
    
        for dic in itemSettings {
            guard let imageName = dic["imageName"] else {continue}
            
            let image = UIImage(named: imageName)
            let hImage = UIImage(named: imageName + "_highlighted")
            
            let btn = UIButton(type: .custom)
            btn.setImage(image, for: .normal)
            btn.setImage(hImage, for: .highlighted)
            
            btn.sizeToFit()
            
            if let actionName = dic["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            toolbar.items?.append(UIBarButtonItem(customView: btn))
            
            // 添加弹簧
            toolbar.items?.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        // 删除系统自带的item
        toolbar.items?.removeFirst()
        // 删除末尾多余的弹簧
        toolbar.items?.removeLast()
    }
    

}
